package com.shopping.service;

import com.shopping.dao.UserMapper;
import com.shopping.entity.User;
import com.shopping.exception.GlobalException;
import com.shopping.redis.UserKey;
import com.shopping.response.CodeMsg;
import com.shopping.utils.MD5Utils;
import com.shopping.utils.RedisService;
import com.shopping.utils.UUIDUtils;
import com.shopping.vo.LoginVO;
import com.sun.tools.javac.jvm.Code;
import jdk.nashorn.internal.objects.Global;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserService {

    public static final String COOKIE_NAME="token";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;

    public User getById(Long id){
        return userMapper.getById(id);
    }

    public boolean login(HttpServletResponse response,LoginVO loginVO){
        if(loginVO==null){
            throw new GlobalException(CodeMsg.SERVER_ERROR);
//            return CodeMsg.SERVER_ERROR;
        }
        String mobile=loginVO.getMobile();
        String formPass=loginVO.getPassword();
        //判断手机号是否存在
        User user = getById(Long.parseLong(mobile));
        if(user==null){
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXISTS);
//            return CodeMsg.MOBILE_NOT_EXISTS;
        }

        //验证密码
        String password=user.getPassword();
        String salt=user.getSalt();
        String calcPass = MD5Utils.fromPassInputPass(formPass, salt);
        if(!StringUtils.equals(password,calcPass)){
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
//            return CodeMsg.PASSWORD_ERROR;
        }

        //添加cookie
        addCookie(response,user);
        return true;

    }

    public User getToken(HttpServletResponse response,String token) {
        if(StringUtils.isEmpty(token)){
            return null;
        }
        User user = redisService.get(UserKey.token, token, User.class);

        //延长有效期
        if(user!=null){
            addCookie(response,user);
        }
        return user;

    }

    private void addCookie(HttpServletResponse response,User user)
    {
        //生成token
        String token = UUIDUtils.uuid();
        redisService.set(UserKey.token,token,user);
        System.out.println(UserKey.token.expireSeconds());

        Cookie cookie=new Cookie(COOKIE_NAME,token);
        cookie.setMaxAge(UserKey.token.expireSeconds());
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
